package com.noble.library.permission.andPermission.install;

import com.noble.library.permission.andPermission.PermissionActivity;
import com.noble.library.permission.andPermission.RequestExecutor;
import com.noble.library.permission.andPermission.source.Source;
import com.noble.library.permission.andPermission.util.MainExecutor;

/**
 * Created by YanZhenjie on 2018/4/28.
 */
class ORequest extends BaseRequest implements RequestExecutor, PermissionActivity.RequestListener {

    private static final MainExecutor EXECUTOR = new MainExecutor();

    private Source mSource;

    ORequest(Source source) {
        super(source);
        this.mSource = source;
    }

    @Override
    public void start() {
        if (mSource.canRequestPackageInstalls()) {
            callbackSucceed();
            install();
        } else {
            showRationale(this);
        }
    }

    @Override
    public void execute() {
        PermissionActivity.requestInstall(mSource.getContext(), this);
    }

    @Override
    public void cancel() {
        callbackFailed();
    }

    @Override
    public void onRequestCallback() {
        EXECUTOR.postDelayed(() -> dispatchCallback(), 100);
    }

    private void dispatchCallback() {
        if (mSource.canRequestPackageInstalls()) {
            callbackSucceed();
            install();
        } else {
            callbackFailed();
        }
    }
}